local voucherId = ARGV[1]
local userId = ARGV[2]
local orderId = ARGV[3]

-- 库存key
local stockKey = "seckill:stock:" .. voucherId
local orderKey = "seckill:order:" .. voucherId

-- 获取当前Redis服务器时间
local serverTime = redis.call('time')
local currentTime = tonumber(serverTime[1])
local beginTime = tonumber(redis.call('hget', stockKey, 'beginTime'))
local endTime = tonumber(redis.call('hget', stockKey, 'endTime'))
-- 判断活动是否开始
if (currentTime < beginTime) then
    return 3
end
-- 判断活动是否结束
if (currentTime > endTime) then
    return 4
end

-- 判断库存是否充足
if (tonumber(redis.call('hget', stockKey, 'stock')) <= 0) then
    return 1
end

-- 判断用户是否下过单
if (redis.call('sismember', orderKey, userId) == 1) then
    return 2
end

-- 扣库存
redis.call('hincrby', stockKey, 'stock', '-1')
-- 保存用户信息到order
redis.call('sadd', orderKey, userId)
return 0